﻿using System;
using System.Collections.Generic;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using CP_SchoolForChildren_v0._1.Controllers.Support;
using CP_SchoolForChildren_v0._1.Models.DataModel;
using CP_SchoolForChildren_v0._1.Models.RelatedModel;
using System.Net;
using System.Globalization;
using PagedList;

namespace CP_SchoolForChildren_v0._1.Controllers.FE
{
    public class SchoolController : Controller
    {
        FunctionController fc = new FunctionController();

        [HttpGet]
        public ActionResult SearchByName(int? page, string schoolName, string sortOrder)
        {
            try
                {
                    ViewBag.CurrentSort = sortOrder;
                    ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Name desc" : "";
                    ViewBag.RateSortParm = String.IsNullOrEmpty(sortOrder) ? "Rate desc" : "";
                    ViewBag.FeeSortParm = String.IsNullOrEmpty(sortOrder) ? "Fee desc" : "";

                    var keywords = schoolName.Split(' ');
                    var record = from sc in fc.db.Schools
                                 join st in fc.db.SchoolTypes on sc.TypeID equals st.TypeID
                                 join dis in fc.db.Districts on sc.DistrictID equals dis.DistrictID
                                 join ct in fc.db.Cities on dis.CityID equals ct.CityID
                                 join syr in fc.db.SystemRatings on sc.SchoolID equals syr.SchoolID
                                 where keywords.Any(val => sc.SchoolName.Contains(val))
                                 orderby sc.SchoolName
                                 select new SeachSchoolModel()
                                 {
                                     SchoolID = sc.SchoolID,
                                     SchoolName = sc.SchoolName,
                                     TypeName = st.TypeName,
                                     Address = sc.Address,
                                     DistrictName = dis.DistrictName,
                                     CityName = ct.CityName,
                                     SystemRate = syr.SystemRate,
                                     TuitionFee = sc.TuitionFee,
                                 };
                    switch (sortOrder)
                    {
                        case "Name desc":
                            record = record.OrderByDescending(s => s.SchoolName);
                            break;
                        case "Rate":
                            record = record.OrderBy(s => s.SystemRate);
                            break;
                        case "Rate desc":
                            record = record.OrderByDescending(s => s.SystemRate);
                            break;
                        case "Fee":
                            record = record.OrderBy(s => s.TuitionFee);
                            break;
                        case "Fee desc":
                            record = record.OrderByDescending(s => s.TuitionFee);
                            break;
                        default:
                            record = record.OrderBy(s => s.SchoolName);

                            break;
                    }
                    ViewBag.schoolName = schoolName;
                    ViewBag.sortOrder = sortOrder;
                    ViewBag.Count = record.Count();
                    int pageSize = 10;
                    int pageNumber = (page ?? 1);

                    // ajax request
                    if (Request.IsAjaxRequest())
                    {
                        return PartialView("SearchByNameResult",record.ToPagedList(pageNumber, pageSize));
                    }
                    //none ajax request
                    return View(record.ToPagedList(pageNumber, pageSize));
                }
                catch (Exception)
                {
                    return View("Error");
                }         
        }

        //
        // GET: /Search By Condition/

        public ActionResult Condition()
        {
            return View();
        }
        
        [HttpGet]
        public ActionResult SearchConditionResult(int CityID, int DistrictID, int SchoolTypeID, int Fee, List<int> ServiceID, int? page, string sortOrder)
        {
            
                try
                {

                    ViewBag.CurrentSort = sortOrder;
                    ViewBag.CityID = CityID;
                    ViewBag.DistrictID = DistrictID;
                    ViewBag.SchoolTypeID = SchoolTypeID;
                    ViewBag.Fee = Fee;
                    List<int> service = ServiceID;
                    ViewBag.ServiceID = service;
                    

                    ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Name desc" : "";
                    ViewBag.RateSortParm = String.IsNullOrEmpty(sortOrder) ? "Rate desc" : "";
                    ViewBag.FeeSortParm = String.IsNullOrEmpty(sortOrder) ? "Fee desc" : "";

                    if (ServiceID == null)
                    {
                        ServiceID = fc.ListService();
                    }
                    

                    double FeeKara = 0;
                    double FeeMade = 0;
                    switch (Fee)
                    {
                        case 2:
                            FeeKara = 0;
                            FeeMade = 1000;
                            break;
                        case 3:
                            FeeKara = 1000;
                            FeeMade = 2000;
                            break;
                        case 4:
                            FeeKara = 2000;
                            FeeMade = 3000;
                            break;
                        case 5:
                            FeeKara = 3000;
                            FeeMade = 4000;
                            break;
                        case 6:
                            FeeKara = 4000;
                            FeeMade = 5000;
                            break;
                        case 7:
                            FeeKara = 5000;
                            FeeMade = 5000;
                            break;

                    }

                    var tmp_school = (from sch in fc.db.Schools
                                      join svr in fc.db.SchoolServices on sch.SchoolID equals svr.SchoolID
                                      where ServiceID.Contains(svr.ServiceID)
                                      select sch.SchoolID).Distinct().ToList();

                    var record = (from s in fc.db.Schools
                                  join st in fc.db.SchoolTypes on s.TypeID equals st.TypeID
                                  join d in fc.db.Districts on s.DistrictID equals d.DistrictID
                                  join c in fc.db.Cities on d.CityID equals c.CityID
                                  join syr in fc.db.SystemRatings on s.SchoolID equals syr.SchoolID
                                  where tmp_school.Contains(s.SchoolID)
                                  orderby s.SchoolName
                                  select new SeachSchoolModel()
                                  {
                                      SchoolID = s.SchoolID,
                                      SchoolName = s.SchoolName,
                                      TypeName = st.TypeName,
                                      Address = s.Address,
                                      DistrictName = d.DistrictName,
                                      CityName = c.CityName,
                                      SystemRate = syr.SystemRate,
                                      CityID = c.CityID,
                                      DistrictID = d.DistrictID,
                                      SchoolTypeID = st.TypeID,
                                      TuitionFee = s.TuitionFee
                                  });


                    int s12 = record.Count();
                    if (CityID > 1)
                        record = record.Where(r => r.CityID == CityID);
                    s12 = record.Count();
                    if (DistrictID > 1)
                        record = record.Where(r => r.DistrictID == DistrictID);
                    s12 = record.Count();
                    if (SchoolTypeID > 1)
                        record = record.Where(r => r.SchoolTypeID == SchoolTypeID);
                    s12 = record.Count();
                    if (FeeKara < FeeMade)
                        record = record.Where(r => r.TuitionFee >= FeeKara).Where(r => r.TuitionFee <= FeeMade);
                    else if (FeeKara == FeeMade && FeeKara > 0)
                        record = record.Where(r => r.TuitionFee >= FeeKara);
                    s12 = record.Count();
                    var tmp = record.ToList();

                    switch (sortOrder)
                    {
                        case "Name desc":
                            record = record.OrderByDescending(s => s.SchoolName);
                            break;
                        case "Rate":
                            record = record.OrderBy(s => s.SystemRate);
                            break;
                        case "Rate desc":
                            record = record.OrderByDescending(s => s.SystemRate);
                            break;
                        case "Fee":
                            record = record.OrderBy(s => s.TuitionFee);
                            break;
                        case "Fee desc":
                            record = record.OrderByDescending(s => s.TuitionFee);
                            break;
                        default:
                            record = record.OrderBy(s => s.SchoolName);

                            break;
                    }
                    int pageSize = 10;
                    int pageNumber = (page ?? 1);
                    ViewBag.Count = record.Count();
                    if (Request.IsAjaxRequest())
                    {
                        return PartialView("SearchCondition", record.ToPagedList(pageNumber, pageSize));
                    }
                    return View(record.ToPagedList(pageNumber, pageSize));
                }
                catch (Exception)
                {
                    return View();
                }
            
        }

        //
        //GET: Detail/
        [HttpGet]
        public ActionResult Detail(int schoolID)
        {
            try
            {
                List<Service> listservice = (from s1 in fc.db.Services 
                                   join ss in fc.db.SchoolServices on s1.ServiceID equals ss.ServiceID
                                   join s in fc.db.Schools on ss.SchoolID equals s.SchoolID
                                   where s.SchoolID == schoolID
                                   select s1).ToList<Service>();
                ViewBag.listservice = listservice;
                var comment = (from c in fc.db.Comments
                         join u in fc.db.Users on c.UserID equals u.UserID
                         where c.SchoolID == schoolID
                         select new CommentDetail()
                         {
                             CreatedTime = c.CreatedTime,
                             CommentContent = c.CommentContent,
                             UserName = u.UserName,
                             TimeOfReport = c.TimeOfReport,
                             CommentID = c.CommentID,
                             UserID = u.UserID
                         }).ToList();
                ViewBag.comment = comment;
                List<SocialRating> socialrate = (from sr in fc.db.SocialRatings
                                        where sr.SchoolID == schoolID
                                        select sr).ToList<SocialRating>();
                ViewBag.socialrate = socialrate;
                var systemRate = (from syr in fc.db.SystemRatings
                                  where syr.SchoolID == schoolID
                                  select syr.SystemRate).ToArray();
                ViewBag.systemRate = systemRate[0];
                var socialRate = (from sr in fc.db.SocialRatings
                                  where sr.SchoolID == schoolID
                                  select sr.SocialRate).ToArray();
                if (socialRate.Count() > 0)
                {
                    double totalStar = 0, star;
                    for (int f = 0; f < socialRate.Count(); f++)
                    {
                        totalStar += socialRate[f];
                    }
                    star = totalStar / socialRate.Count();
                    ViewBag.star = star;
                }
                else {
                    double star = 0;
                    ViewBag.star = star;
                }
                var getSchoolID = (from s in fc.db.Schools
                                   where s.SchoolID == schoolID
                                   select s.SchoolID).ToArray();
                ViewBag.getSchoolID = getSchoolID[0];
                var school = (from s in fc.db.Schools
                              join st in fc.db.SchoolTypes on s.TypeID equals st.TypeID
                              join d in fc.db.Districts on s.DistrictID equals d.DistrictID
                              join c in fc.db.Cities on d.CityID equals c.CityID
                              where s.SchoolID == schoolID
                              select new DetailOfSchool()
                              {
                                  SchoolID = s.SchoolID,
                                  SchoolName = s.SchoolName,
                                  TypeName = st.TypeName,
                                  Address = s.Address,
                                  Phone = s.Phone,
                                  DistrictName = d.DistrictName,
                                  CityName = c.CityName,
                                  Website = s.Website,
                                  Email = s.Email,
                                  Principal = s.Principal,
                                  Program = s.Program,
                                  Area = s.Area,
                                  EnrollmentTime = s.EnrollmentTime,
                                  AcceptAgeDescription = s.AcceptAgeDescription,
                                  EstablishYear = s.EstablishYear,
                                  NumberOfTeacher = s.NumberOfTeacher,
                                  NumberOfChildren = s.NumberOfChildren,
                                  TuitionFee = s.TuitionFee,
                                  GoogleAPI = s.GoogleAPI,
                                  Description = s.Description
                              }).ToList();
                var admission = (from s in fc.db.Schools
                                  join st in fc.db.SchoolTypes on s.TypeID equals st.TypeID
                                  join d in fc.db.Districts on s.DistrictID equals d.DistrictID
                                  join c in fc.db.Cities on d.CityID equals c.CityID
                                  where s.SchoolID == schoolID
                                  select s.Admission).ToList();
                string correctAdmission = "";
                correctAdmission = admission[0].Replace("</br></br>", ". ");
                ViewBag.correctAdmission = correctAdmission;
                return View(school.First());
            }
            catch (Exception)
            {
                return View();
            }
        }

        //
        //POST: Detail/
        [HttpPost]
        public ActionResult Detail(int schoolID, string Comment_Content)
        {
            try
            {
                if (!string.IsNullOrEmpty(Comment_Content) && !string.IsNullOrWhiteSpace(Comment_Content) && Comment_Content.Length <= 1000)
                {
                    var getUserID = (from u in fc.db.Users
                                         where u.UserName == User.Identity.Name
                                         select u.UserID).First();
                    int userid = getUserID;
                    Comment newComment = new Comment();
                    newComment.CreatedTime = DateTime.Now;
                    newComment.UserID = userid;
                    newComment.SchoolID = schoolID;
                    newComment.CommentContent = Comment_Content;
                    newComment.TimeOfReport = 0;
                    newComment.CommentStatus = 1;

                    fc.db.Comments.Add(newComment);
                    fc.db.SaveChanges();
                    return RedirectToAction("Detail", "School", new {schoolID = schoolID});
                }
            }
            catch (Exception)
            {
                return View();
            }

            return RedirectToAction("Detail", "School", new {schoolID = schoolID});
        }

        //
        public string EditComment(string id, string value, int CommentId, string RecordType)
        {
            var comment = (from a in fc.db.Comments
                          where a.CommentID == CommentId
                          select a).First();
            try
            {
                comment.CommentContent = value;
                fc.db.Entry(comment).State = System.Data.EntityState.Modified;
                fc.db.SaveChanges();
                return value;
            }
            catch (Exception)
            {
                return null;
            }

        }
        //POST: Delete Comment/
       
        public ActionResult DeleteComment(int commentID)
        {
            try
            {
                var del_comment = (from c in fc.db.Comments
                                   where c.CommentID == commentID
                                   select c).ToList();
                int schoolID = del_comment.First().SchoolID;
                foreach (var item in del_comment)
                {
                    fc.db.Comments.Remove(item);
                }
                fc.db.SaveChanges();
                return RedirectToAction("Detail", "School", new { schoolID = schoolID });
            }
            catch (Exception)
            {
                return View("Error");
            }
        }

        //
        //POST: Rating/
        [HttpPost]
        public double Rating(int socialRate, int schoolID)
        {
            try
            {
                double totalStar = 0, star;
                int f;
                var getUserID = (from u in fc.db.Users
                                 where u.UserName == User.Identity.Name
                                 select u.UserID).ToArray();
                int userid = getUserID[0];
                var checkRate_OrNot = (from sr10 in fc.db.SocialRatings
                                       where sr10.UserID == userid && sr10.SchoolID == schoolID
                                       select sr10).ToArray();
                if (checkRate_OrNot.Count() == 0)
                {
                    SocialRating rate = new SocialRating();
                    rate.SchoolID = schoolID;
                    rate.SocialRate = socialRate;
                    rate.UserID = userid;

                    fc.db.SocialRatings.Add(rate);
                    fc.db.SaveChanges();
                    var socialRate1 = (from sr in fc.db.SocialRatings
                                       where sr.SchoolID == schoolID
                                       select sr.SocialRate).ToArray();
                    for (f = 0; f < socialRate1.Count(); f++)
                    {
                        totalStar += socialRate1[f];
                    }
                    star = totalStar / socialRate1.Count();
                    return star;
                }
                else
                {
                    foreach (var detail in checkRate_OrNot)
                    {
                        fc.db.SocialRatings.Remove(detail);
                    }

                    try
                    {
                        fc.db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                    SocialRating rate = new SocialRating();
                    rate.SchoolID = schoolID;
                    rate.SocialRate = socialRate;
                    rate.UserID = userid;

                    fc.db.SocialRatings.Add(rate);
                    fc.db.SaveChanges();
                    var socialRate1 = (from sr in fc.db.SocialRatings
                                       where sr.SchoolID == schoolID
                                       select sr.SocialRate).ToArray();
                    for (f = 0; f < socialRate1.Count(); f++)
                    {
                        totalStar += socialRate1[f];
                    }
                    star = totalStar / socialRate1.Count();
                    return star;
                }
            }
            catch (Exception) {
                return 1;
            }
        }

        //
        //POST: Report School/
        [HttpPost]
        public string Report(int schoolID, string report_cnt)
        {
            try
            {
                string host = Dns.GetHostName();
                IPHostEntry ip = Dns.GetHostEntry(host);
                string strClientIP = ip.AddressList[0].ToString();
                ReportSchool rs = new ReportSchool();
                rs.SchoolID = schoolID;
                rs.ReportContent = report_cnt;
                rs.CreatedTime = DateTime.Now;
                rs.AuthorIP = strClientIP;
                fc.db.ReportSchools.Add(rs);
                fc.db.SaveChanges();
                return "Hệ thống đã ghi nhận và BQT sẽ xem xét trong thời gian sớm nhất. Cảm ơn sự đóng góp của bạn."; 
            }
            catch (Exception)
            {
                return "Rất tiếc. Hệ thống đã xảy ra lỗi. Xin bạn vui lòng thử lại sau.";
            }
        }

        //
        //POST: Report Comment/
        [HttpPost]
        public string ReportComment(int commentID, string report_cnt, int schoolID)
        {
            try
            {
                string host = Dns.GetHostName();
                IPHostEntry ip = Dns.GetHostEntry(host);
                string strClientIP = ip.AddressList[0].ToString();
                ReportComment rc = new ReportComment();
                rc.CommentID = commentID;
                rc.ReportCommentContent = report_cnt;
                rc.CreatedTime = DateTime.Now;
                rc.AuthorIP = strClientIP;
                fc.db.ReportComments.Add(rc);
                fc.db.SaveChanges();
                return "Hệ thống đã ghi nhận và BQT sẽ xem xét trong thời gian sớm nhất. Cảm ơn sự đóng góp của bạn.";
            }
            catch (Exception) {
                return "Rất tiếc. Hệ thống đã xảy ra lỗi. Xin bạn vui lòng thử lại sau.";
            }
        }

        //
        //GET: Compare/
        [HttpGet]
        public ActionResult Compare(string ListSchool)
        {
            try
            {
                var temp = ListSchool.Split(',');
                var listSID = new List<int>();
                for(int i = 0 ; i < temp.Count(); i++)
                {
                    if(listSID.Count < 4){
                    listSID.Add(int.Parse(temp.ElementAt(i)));
                    }
                }

                var school = (from s in fc.db.Schools
                              join st in fc.db.SchoolTypes on s.TypeID equals st.TypeID
                              join d in fc.db.Districts on s.DistrictID equals d.DistrictID
                              join c in fc.db.Cities on d.CityID equals c.CityID
                              where listSID.Contains(s.SchoolID)
                              select new DetailOfSchool()
                              {
                                  SchoolID = s.SchoolID,
                                  SchoolName = s.SchoolName,
                                  TypeName = st.TypeName,
                                  Address = s.Address,
                                  Phone = s.Phone,
                                  DistrictName = d.DistrictName,
                                  CityName = c.CityName,
                                  Website = s.Website,
                                  Email = s.Email,
                                  Principal = s.Principal,
                                  Program = s.Program,
                                  Area = s.Area,
                                  EnrollmentTime = s.EnrollmentTime,
                                  AcceptAgeDescription = s.AcceptAgeDescription,
                                  Admission = s.Admission,
                                  EstablishYear = s.EstablishYear,
                                  NumberOfTeacher = s.NumberOfTeacher,
                                  NumberOfChildren = s.NumberOfChildren,
                                  TuitionFee = s.TuitionFee,
                                  GoogleAPI = s.GoogleAPI,
                                  Description = s.Description
                              }).ToList();
                return View(school.OrderByDescending(s => s.TuitionFee));
            }
            catch (Exception)
            {
                return View();
            }
        }

        //
        //Add Schools To Favourite List /
        public string AddToFavourite(int schoolID) {
            try
            {
                var getUserID = (from u in fc.db.Users
                                 where u.UserName == User.Identity.Name
                                 select u.UserID).ToArray();
                int userid = getUserID[0];
                var getList = (from f_l in fc.db.FavoriteLists
                               where f_l.SchoolID == schoolID && f_l.UserID == userid
                               select f_l.SchoolID).ToArray();
                var getList1 = (from f_l in fc.db.FavoriteLists
                               where f_l.UserID == userid
                               select f_l.SchoolID).ToArray();
                if (getList.Count() > 0)
                {
                    return "Trường này đã có sẵn trong danh sách ưa thích của bạn.";
                }
                else
                {
                    if (getList1.Count() >= 20)
                    {
                        return "Danh sách đã đầy. Bạn cần xóa bớt các trường trước khi thêm.";
                    }
                    else
                    {
                        FavoriteList fl = new FavoriteList();
                        fl.SchoolID = schoolID;
                        fl.UserID = userid;

                        fc.db.FavoriteLists.Add(fl);
                        fc.db.SaveChanges();
                        return "Đã thêm vào danh sách ưa thích của bạn.";
                    }
                }
            }
            catch (Exception) {
                return "Rất tiếc. Hệ thống đã xảy ra lỗi. Xin bạn vui lòng thử lại sau.";
            }
        }

        //
        //GET: Search by map/
        public ActionResult Map() {
            return View();
        }

        //
        //GET: Search By Map at New Tab/
        [HttpGet]
        public JsonResult MapControl(double lat, double lng, int radius)
        {
            try
            {
                double[] getGet = new double[219];
                double[] getGet1 = new double[219];
                double[] valueAll = new double[100];
                string[] splitAPI = new string[] { };
                char[] delimiters = new char[] { ',', ' ' };
                List<DetailOfSchool> takeAll10 = new List<DetailOfSchool>();
                List<DetailOfSchool> takeAll100 = new List<DetailOfSchool>();
                const double RAD = Math.PI / 180;
                var takeAll = (from s in fc.db.Schools
                               select s.GoogleAPI).ToArray();
                for (int j = 0; j < takeAll.Length; j++)
                {
                    splitAPI = takeAll[j].Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                    getGet[j] = Double.Parse(splitAPI[0], CultureInfo.InvariantCulture);
                    getGet1[j] = Double.Parse(splitAPI[1], CultureInfo.InvariantCulture);
                    var lat1 = (getGet[j] - lat) * RAD;
                    var lng1 = (getGet1[j] - lng) * RAD;
                    var h1 = Math.Sin(lat1 / 2) * Math.Sin(lat1 / 2) +
                                  Math.Cos(lat) * Math.Cos(lat) *
                                  Math.Sin(lng1 / 2) * Math.Sin(lng1 / 2);
                    var h2 = 6371 * 2 * Math.Asin(Math.Min(1, Math.Sqrt(h1)));
                    string aaa = takeAll[j];
                    takeAll10 = (from s in fc.db.Schools
                                 let distance = h2
                                 where s.GoogleAPI == aaa && distance < radius
                                 select new DetailOfSchool
                                 {
                                     SchoolName = s.SchoolName,
                                     Address = s.Address,
                                     GoogleAPI = s.GoogleAPI
                                 }).ToList<DetailOfSchool>();
                    takeAll100.AddRange(takeAll10);
                    takeAll100.Count();
                }
                return Json(new { Result = "OK", Options = takeAll100 }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new { Result = "ERROR" });
            }
        }

        //
        //GET: Search By Map at Index/
        [HttpGet]
        public ActionResult SearchByMap(int? page,double lat, double lng, int radius, string sortOrder)
        {
            try
                {
                    ViewBag.CurrentSort = sortOrder;
                    ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Name desc" : "";
                    ViewBag.RateSortParm = String.IsNullOrEmpty(sortOrder) ? "Rate desc" : "";
                    ViewBag.FeeSortParm = String.IsNullOrEmpty(sortOrder) ? "Fee desc" : "";
                    //double[] getGet = new double[220];
                    //double[] getGet1 = new double[220];
                   
                    string[] splitAPI = new string[] { };
                    char[] delimiters = new char[] { ',', ' ' };
                    //List<int> takeAll10 = new List<SeachSchoolModel>();
                    List<SeachSchoolModel> takeAll100 = new List<SeachSchoolModel>();
                    const double RAD = Math.PI / 180;
                    var takeAll = (from s in fc.db.Schools
                                   select s.GoogleAPI).ToArray();
                    var listSC = new List<int>();
                    for (int j = 0; j < takeAll.Length; j++)
                    {
                        splitAPI = takeAll[j].Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                        double getGet = Double.Parse(splitAPI[0], CultureInfo.InvariantCulture);
                        double getGet1 = Double.Parse(splitAPI[1], CultureInfo.InvariantCulture);
                        var lat1 = (getGet - lat) * RAD;
                        var lng1 = (getGet1 - lng) * RAD;
                        var h1 = Math.Sin(lat1 / 2) * Math.Sin(lat1 / 2) +
                                      Math.Cos(lat) * Math.Cos(lat) *
                                      Math.Sin(lng1 / 2) * Math.Sin(lng1 / 2);
                        var h2 = 6371 * 2 * Math.Asin(Math.Min(1, Math.Sqrt(h1)));
                        if (h2 < 2)
                        {
                            string aaa = takeAll[j];
                            var tmp = (from s in fc.db.Schools
                                       where s.GoogleAPI == aaa
                                       select s.SchoolID).ToList().First();
                            listSC.Add(tmp);
                        }
                    }
                    var record = (from s in fc.db.Schools
                                  join st in fc.db.SchoolTypes on s.TypeID equals st.TypeID
                                  join d in fc.db.Districts on s.DistrictID equals d.DistrictID
                                  join c in fc.db.Cities on d.CityID equals c.CityID
                                  join syr in fc.db.SystemRatings on s.SchoolID equals syr.SchoolID
                                  orderby s.SchoolName
                                  where listSC.Contains(s.SchoolID)
                                  select new SeachSchoolModel
                                  {
                                      SchoolID = s.SchoolID,
                                      SchoolName = s.SchoolName,
                                      TuitionFee = s.TuitionFee,
                                      TypeName = st.TypeName,
                                      Address = s.Address,
                                      DistrictName = d.DistrictName,
                                      CityName = c.CityName,
                                      SystemRate = syr.SystemRate
                                  });

                    switch (sortOrder)
                    {
                        case "Name desc":
                            record = record.OrderByDescending(s => s.SchoolName);
                            break;
                        case "Rate":
                            record = record.OrderBy(s => s.SystemRate);
                            break;
                        case "Rate desc":
                            record = record.OrderByDescending(s => s.SystemRate);
                            break;
                        case "Fee":
                            record = record.OrderBy(s => s.TuitionFee);
                            break;
                        case "Fee desc":
                            record = record.OrderByDescending(s => s.TuitionFee);
                            break;
                        default:
                            record = record.OrderBy(s => s.SchoolName);

                            break;
                    }
                    ViewBag.Count = record.Count();

                    int pageSize = 10;
                    int pageNumber = (page ?? 1);
                    ViewBag.radius = radius;
                    ViewBag.lat = lat;
                    ViewBag.lng = lng;
                    if (Request.IsAjaxRequest())
                    {
                        return PartialView("MapResult", record.ToPagedList(pageNumber, pageSize));
                    }

                    return View(record.ToPagedList(pageNumber,pageSize));
                 }
                catch (Exception)
                {
                    return View();
                }   
        }



        [HttpGet]
        public JsonResult GetThePoint(double lat, double lng, int radius)
        {
            try
            {
                //double[] getGet = new double[220];
                //double[] getGet1 = new double[220];
                //double[] valueAll = new double[100];
                string[] splitAPI = new string[] { };
                char[] delimiters = new char[] { ',', ' ' };
                //List<int> takeAll10 = new List<SeachSchoolModel>();
                List<SeachSchoolModel> takeAll100 = new List<SeachSchoolModel>();
                const double RAD = Math.PI / 180;
                var takeAll = (from s in fc.db.Schools
                               select s.GoogleAPI).ToArray();
                var listSC = new List<int>();
                for (int j = 0; j < takeAll.Length; j++)
                {
                    splitAPI = takeAll[j].Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                    double getGet = Double.Parse(splitAPI[0], CultureInfo.InvariantCulture);
                    double getGet1 = Double.Parse(splitAPI[1], CultureInfo.InvariantCulture);
                    var lat1 = (getGet - lat) * RAD;
                    var lng1 = (getGet1 - lng) * RAD;
                    var h1 = Math.Sin(lat1 / 2) * Math.Sin(lat1 / 2) +
                                  Math.Cos(lat) * Math.Cos(lat) *
                                  Math.Sin(lng1 / 2) * Math.Sin(lng1 / 2);
                    var h2 = 6371 * 2 * Math.Asin(Math.Min(1, Math.Sqrt(h1)));
                    if (h2 < 2)
                    {
                        string aaa = takeAll[j];
                        var tmp = (from s in fc.db.Schools
                                   where s.GoogleAPI == aaa
                                   select s.SchoolID).ToList().First();
                        listSC.Add(tmp);
                    }
                }
                var record = from s in fc.db.Schools
                             where listSC.Contains(s.SchoolID)
                             select new
                             {
                                 Name = s.SchoolName,
                                 API = s.GoogleAPI
                             };

                return Json(new { Result = "OK", Record = record }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", message = "Có lỗi xảy ra trong quá trình tìm kiếm, vui lòng thử lại sau ít phút"}, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
